import BaseModel from 'base/models/BaseModel'
import Radio from 'backbone.radio';
import {
    isCancelinvoice
} from './utils';


const ProductModel = BaseModel.extend({
    // Define the props that should be set on your model
    props: [
        'id',
        'chapter_id',
        "type_",
        'description',
        'unity',
        'quantity',
        'tva',
        'product_id',
        "percentage",
        "already_invoiced", // avant cette facture
        // Dans l'affaire
        'total_ht_to_invoice',
        'total_tva_to_invoice',
        'total_ttc_to_invoice',
        // Après cette facture
        'percent_left',
        'total_ht_left',
        'total_ht',
        'tva_amount',
        'total_ttc',
        // "Acompte ?"
        "has_deposit",
    ],
    validation: function () {
        let range;
        const already_invoiced = this.get('already_invoiced') || 0;
        if (isCancelinvoice()) {
            range = [-1 * already_invoiced, 0]
        } else {
            range = [0, 100 - already_invoiced]
        }
        return {
            'percentage': {
                required: true,
                range: range,
                msg: `Veuillez saisir un pourcentage entre ${range[0]} et ${range[1]}`,
            }
        }
    },
    initialize: function () {
        ProductModel.__super__.initialize.apply(this, arguments);
        this.config = Radio.channel('config');
        this.tva_options = this.config.request('get:options', 'tvas');
        this.product_options = this.config.request('get:options', 'products');
        this.user_prefs = Radio.channel('user_preferences');
    },
    product_object() {
        let product_id = parseInt(this.get('product_id'));
        return this.product_options.find((value) => product_id == value.id);
    },
    tva_object() {
        let tva_id = parseInt(this.get('tva_id'));
        return this.tva_options.find((value) => tva_id == value.id);
    },
    tva_label() {
        return this.findLabelFromId('tva_id', 'label', this.tva_options);
    },
    _price_label(key) {
        return this.user_prefs.request('formatAmount', this.get(key), false);
    },
    total_ht_to_invoice_label() {
        return this._price_label('total_ht_to_invoice')
    },
    tva_to_invoice_label() {
        return this._price_label('total_tva_to_invoice')
    },
    total_ttc_to_invoice_label() {
        return this._price_label('total_ttc_to_invoice')
    },
    total_ht_label() {
        return this._price_label('total_ht');
    },
    tva_label() {
        return this._price_label('tva_amount');
    },
    total_ttc_label() {
        return this._price_label('total_ttc');
    }
})
export default ProductModel;